package com.czh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czh.constants.SystemConstants;
import com.czh.domain.ResponseResult;
import com.czh.domain.dto.AddArticleDto;
import com.czh.domain.dto.QueryArticleDto;
import com.czh.domain.entity.Article;
import com.czh.domain.entity.ArticleTag;
import com.czh.domain.vo.*;
import com.czh.mapper.ArticleMapper;
import com.czh.service.ArticleService;
import com.czh.service.ArticleTagService;
import com.czh.service.CategoryService;
import com.czh.utils.BeanCopyUtils;
import com.czh.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 文章表(Article)表服务实现类
 *
 * @author makejava
 * @since 2024-03-17 22:56:55
 */
@Service("articleService")
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService{
    @Lazy
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleTagService articleTagService;

    @SuppressWarnings("unchecked")
    //热门文章名
    @Override
    public ResponseResult<List<HotArticleVo>> hotArticleList() {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL).orderByDesc(Article::getViewCount);
        List<Article> articleList = page(new Page<>(1, 5), queryWrapper).getRecords();
        //将bean拷贝给另一个
        List<HotArticleVo> hotArticleVos = BeanCopyUtils.copyBeanList(articleList, HotArticleVo.class);
        return ResponseResult.okResult(hotArticleVos);
    }
    @Override
    //查询热门文章
    public ResponseResult<ArticlePageVo<ArticleShowVo>> articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        LambdaQueryWrapper<Article> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //为false时忽略条件
        articleLambdaQueryWrapper.eq(Objects.nonNull(categoryId)&&categoryId>0, Article::getCategoryId,categoryId);
        // 需要是正式发布的文章
        articleLambdaQueryWrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        //以isTop进行降序
        articleLambdaQueryWrapper.orderByDesc(Article::getIsTop);
        //分页查询
        Page<Article> articlePage = page(new Page<>(pageNum, pageSize),articleLambdaQueryWrapper);
        //这里会有问题
        Map<String, Integer> cacheMap = redisCache.getCacheMap("article:viewCount");
//        List<Article> articleList1 = articlePage.getRecords();
        //查询文章分类名categoryName和redis中更新的浏览量并赋值给每个Article
        List<Article> articleList = articlePage.getRecords().stream()
                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()).
                        setViewCount(Long.valueOf(cacheMap.get(article.getId().toString()))))
                .collect(Collectors.toList());
//        for (Article article : articleList) {
//            String name = categoryService.getById(article.getCategoryId()).getName();
//            article.setCategoryName(name);
//        }
        List<ArticleShowVo> articleShowVos = BeanCopyUtils.copyBeanList(articleList, ArticleShowVo.class);
        ArticlePageVo<ArticleShowVo> articlePageVo = new ArticlePageVo<>(articleShowVos, articlePage.getTotal());
        return ResponseResult.okResult(articlePageVo);
    }
    //文章详情
    @Override
    public ResponseResult<ArticleShowDetailVo> getArticleDetail(Long id) {
        Article article = getById(id);
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString());
        //默认文章表是没有文章分类名的,需要查一下分类名
        String categoryName = categoryService.getById(article.getCategoryId()).getName();
        article.setCategoryName(categoryName).setViewCount(viewCount.longValue());
        ArticleShowDetailVo articleShowDetailVo = BeanCopyUtils.copyBean(article, ArticleShowDetailVo.class);
        return ResponseResult.okResult(articleShowDetailVo);
    }

    @Override
    public ResponseResult<Object> updateViewCount(Long id) {
        redisCache.incrementCacheMapValue("article:viewCount",id.toString(),1);
        return ResponseResult.okResult();
    }
    /**
     *admin
     */
    @Override
    @Transactional
    public ResponseResult<Object> addArticle(AddArticleDto addArticleDto) {
        Article article = BeanCopyUtils.copyBean(addArticleDto, Article.class);
        save(article);

        List<ArticleTag> list = addArticleDto.getTags().stream().map(tags -> new ArticleTag(article.getId(), tags)).collect(Collectors.toList());
        articleTagService.saveBatch(list);
        //浏览量要更新
        Map<String, Integer> map = list().
                stream().collect(Collectors.toMap(article1 -> article1.getId().toString(), article1 -> article1.getViewCount().intValue()));
        redisCache.setCacheMap("article:viewCount", map);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<ArticlePageVo<ArticleManageVo>> pageArticleList(Integer pageNum, Integer pageSize, QueryArticleDto queryArticleDto) {
        LambdaQueryWrapper<Article> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleLambdaQueryWrapper.like(StringUtils.hasText(queryArticleDto.getTitle()), Article::getTitle, queryArticleDto.getTitle());
                articleLambdaQueryWrapper.like(StringUtils.hasText(queryArticleDto.getSummary()),Article::getSummary, queryArticleDto.getSummary());
        Page<Article> articlePage = new Page<>(pageNum, pageSize);
        page(articlePage,articleLambdaQueryWrapper);
        List<ArticleManageVo> collect = BeanCopyUtils.copyBeanList(articlePage.getRecords(),ArticleManageVo.class);
        return ResponseResult.okResult(new ArticlePageVo<>(collect, articlePage.getTotal()));
    }

    @Override
    public ResponseResult<ArticleManageDetailVo> getArticleManageDetail(Long id) {
        List<Long> collect = articleTagService.list().stream().filter(articleTag -> Objects.equals(articleTag.getArticleId(), id)).map(ArticleTag::getTagId).collect(Collectors.toList());
        ArticleManageDetailVo articleManageDetailVo = BeanCopyUtils.copyBean(getById(id), ArticleManageDetailVo.class);
        articleManageDetailVo.setTags(collect);
        return ResponseResult.okResult(articleManageDetailVo);
    }

    @Override
    public ResponseResult<Object> deleteArticle(Long id) {
        removeById(id);
        articleTagService.removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<Object> updateArticle(Article article) {
        LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Article::getId,article.getId());
        update(article,updateWrapper);
        return ResponseResult.okResult();
    }
}